package com.yisoo.ubag.product.service.impl;

import com.yisoo.common.to.DevSimpleDataTo;
import com.yisoo.common.to.RefreshBagStatusTo;
import com.yisoo.common.utils.R;
import com.yisoo.ubag.product.entity.*;
import com.yisoo.ubag.product.feign.IotFeignService;
import com.yisoo.ubag.product.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yisoo.common.utils.PageUtils;
import com.yisoo.common.utils.Query;

import com.yisoo.ubag.product.dao.DevDao;
import org.springframework.util.StringUtils;


@Service("devService")
public class DevServiceImpl extends ServiceImpl<DevDao, DevEntity> implements DevService {

    @Autowired
    BrandService brandService;
    @Autowired
    SceneService sceneService;
    @Autowired
    DevTokenService devTokenService;
    @Autowired
    DevSecBraConService devSecBraConService;


    @Autowired
    IotFeignService iotFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {


        Long cid = Long.valueOf((String)params.get("cid"));
        QueryWrapper<DevEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_cid",cid);


        IPage<DevEntity> page = this.page(
                new Query<DevEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public R quickImport(DevTokenEntity devToken, Integer num) {

        List<DevTokenEntity> residue = devSecBraConService.getResidue(devToken);

        List<DevEntity> collect = residue.stream().map(temp -> {
            DevEntity devEntity = new DevEntity();
            if (temp.getTokenUsing() == 0) {
                devEntity.setDevName(temp.getRunToken().substring(0, 4) + "_box");
            } else {
                devEntity.setDevName(temp.getRunToken().substring(0, 4) + "_bag");
            }
            devEntity.setEnable(temp.getEnable());
            devEntity.setParentCid(temp.getMasterId());
            devEntity.setRunToken(temp.getRunToken());
            devEntity.setDevUsing(temp.getTokenUsing());
            devEntity.setStatus(0);
            devEntity.setCreateTime(new Date());
            return devEntity;
        }).collect(Collectors.toList());

        collect = collect.subList(0, num);
        this.saveBatch(collect);

        //还没完，存到关系表
        //再把表查出来，为了得到id
        List<DevEntity> withDevId = this.getListWithDevId(collect);

        List<DevSecBraConEntity> devSecBraConEntityList = withDevId.stream().map(temp -> {
            DevSecBraConEntity devSecBraConEntity = new DevSecBraConEntity();
            devSecBraConEntity.setDevId(temp.getDevId());
            devSecBraConEntity.setRunToken(temp.getRunToken());
            //根据token查cid sid bid
            DevTokenEntity tokenEntity = devTokenService.getById(temp.getRunToken());
            devSecBraConEntity.setBrandId(tokenEntity.getBrandId());
            devSecBraConEntity.setSceneId(tokenEntity.getSceneId());
            devSecBraConEntity.setConsumerId(tokenEntity.getMasterId());
            devSecBraConEntity.setBrandName(brandService.getById(tokenEntity.getBrandId()).getBrandName());
            devSecBraConEntity.setSceneName(sceneService.getById(tokenEntity.getSceneId()).getSceneName());
            return devSecBraConEntity;
        }).collect(Collectors.toList());

        devSecBraConService.saveBatch(devSecBraConEntityList);
        //导入完成后，该创建设备到云平台了
//        withDevId
        yunIotDevAdd(withDevId.get(0).getParentCid(),withDevId);
        return R.ok();

    }
    //异步访问远程接口
    @Async
    public void yunIotDevAdd(Long cid,List<DevEntity> list){
        List<DevSimpleDataTo> collect = list.stream().map(temp -> {
            DevSimpleDataTo devSimpleDataTo = new DevSimpleDataTo();
            BeanUtils.copyProperties(temp, devSimpleDataTo);
            return devSimpleDataTo;
        }).collect(Collectors.toList());
        iotFeignService.addDev(cid,collect);
    }

    @Override
    public List<DevEntity> getListWithDevId(List<DevEntity> list) {

        List<DevEntity> collect = list.stream().map(temp -> {
            QueryWrapper<DevEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("run_token", temp.getRunToken());
            List<DevEntity> entityList = baseMapper.selectList(queryWrapper);
            temp.setDevId(entityList.get(0).getDevId());
            return temp;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public R activeDev(String devName, Integer status) {

        QueryWrapper<DevEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dev_name", devName);
        List<DevEntity> devEntities = baseMapper.selectList(queryWrapper);
        if(devEntities !=null &&devEntities.size()>0){
            DevEntity entity = devEntities.get(0);
            entity.setStatus(status);
            baseMapper.updateById(entity);
            return R.ok();
        }else{
            return  R.error();
        }

    }

    @Override
    public RefreshBagStatusTo getRel(Long devid) {
        DevEntity devEntity = baseMapper.selectById(devid);
        DevSecBraConEntity devSecBraConEntity = devSecBraConService.getDataById(devid);
        return new RefreshBagStatusTo(
                devid,devEntity.getDevName(),
                devSecBraConEntity.getSceneId(),devSecBraConEntity.getSceneName(),
                devSecBraConEntity.getBrandId(),devSecBraConEntity.getBrandName(),
                null,null,null
        );

    }

    @Override
    public Integer getNumByParentId(Long userid) {
        QueryWrapper<DevEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_cid",userid);
        return  baseMapper.selectList(queryWrapper).size();
    }

    @Override
    public List<DevEntity> getDevByUid(Long uid) {
        QueryWrapper<DevEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_cid",uid);
        return  baseMapper.selectList(queryWrapper);
    }


}